package com.zou.szt;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.zou.szt.Utils.JsonUtils;
import com.zou.szt.Utils.ToastUtil;
import com.zou.szt.Utils.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

/**
 * 。
 * Created by zou on 2016/5/19.
 */
public class MyAdapter extends BaseRecyclerViewAdapter implements MainActivity.OnSwipeRefreshListener {

    private Context context;
    List<String> data;

    private final LayoutInflater inflater;
    FragmentManager fragmentManager;
    List<CardHolder> holders;
    private final RequestQueue requestQueue;

    OnRequestOverListener listener;


    public MyAdapter(List<String> data, Context context, FragmentManager fragmentManager) {
        this.context = context;
        this.data = data;
        inflater = LayoutInflater.from(context);
        this.fragmentManager = fragmentManager;
        holders = new ArrayList<>();
        requestQueue = VolleySingleton.getVolleySingleton(context).getRequestQueue();
        listener = (OnRequestOverListener) context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case 0:
                return new CardHolder(inflater.inflate(R.layout.card, parent, false));
            case 1:
                return new AddHolder(inflater.inflate(R.layout.layout_add, parent, false));
            case 2:
                return new TitleHolder(inflater.inflate(R.layout.item_title, parent, false));
            default:
                return null;
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof CardHolder) {
            ((CardHolder) holder).tv_number.setText(data.get(position - 1));
            holders.add((CardHolder) holder);
            ((CardHolder) holder).getdata();
        } else if (holder instanceof AddHolder) {
//            添加按钮点击事件。。
            ((AddHolder) holder).add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AddDialogFragment addDialogFragment = new AddDialogFragment();
                    addDialogFragment.show(fragmentManager, "Add");
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        if (data == null) {
            return 2;
        } else {
            return data.size() + 2;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return 2;
        } else if (position == data.size() + 1) {
            return 1;
        } else {
            return 0;
        }
    }

    //    下拉刷新时调用
    @Override
    public void getData() {
        for (CardHolder holder : holders) {
            holder.getdata();
        }
    }

    private class CardHolder extends RecyclerView.ViewHolder {

        TextView tv_number;
        TextView tv_money;
        TextView tv_time;
        TextView tv_nickname;
        ProgressBar progressBar;
        RelativeLayout pro_container;
        ImageView rebtn;

        public CardHolder(View itemView) {
            super(itemView);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);
            tv_number = (TextView) itemView.findViewById(R.id.tv_number);
            tv_money = (TextView) itemView.findViewById(R.id.tv_money);
            tv_time = (TextView) itemView.findViewById(R.id.tv_time);
            tv_nickname = (TextView) itemView.findViewById(R.id.tv_nickname);
            pro_container = (RelativeLayout) itemView.findViewById(R.id.pro_container);
            rebtn = (ImageView) itemView.findViewById(R.id.btn_refresh);
            progressBar.setVisibility(View.GONE);

//            添加长按事件
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    RemoveDialogFragment removeDialogFragment = new RemoveDialogFragment();
                    Bundle args = new Bundle();
                    args.putString("number", tv_number.getText().toString());
                    removeDialogFragment.setArguments(args);
                    removeDialogFragment.show(fragmentManager, "Remove");


                    return true;
                }
            });

            rebtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getdata();
                }
            });

        }

        void getdata() {

            progressBar.setVisibility(View.VISIBLE);
            rebtn.setVisibility(View.GONE);


            StringRequest stringRequest = new StringRequest(
                    Constants.URL + tv_number.getText(),
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {
                                progressBar.setVisibility(View.GONE);
                                rebtn.setVisibility(View.VISIBLE);
                                ResultBean data = (ResultBean) JsonUtils.fromJson(response, ResultBean.class);
                                Log.e("wocao", "onResponse: " + tv_number.getText() + "||||" + data.toString());
                                if (TextUtils.equals(data.getCard_number(), "0")) {
                                    tv_money.setText("查询失败");
                                    tv_time.setText("——————");
                                } else {
                                    tv_money.setText(data.getCard_balance());
                                    tv_time.setText(data.getBalance_time());
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                ToastUtil.showToast(context, "服务异常");
                                progressBar.setVisibility(View.GONE);
                                rebtn.setVisibility(View.VISIBLE);
                                tv_money.setText("服务异常");
                                tv_time.setText("——————");
                            }

                            listener.requestOver();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            ToastUtil.showToast(context, "服务异常");
                            progressBar.setVisibility(View.GONE);
                            rebtn.setVisibility(View.VISIBLE);

                            tv_money.setText("服务异常");
                            tv_time.setText("——————");
                        }
                    });
            stringRequest.setShouldCache(true);
            requestQueue.add(stringRequest);
        }
    }

    private class AddHolder extends RecyclerView.ViewHolder {

        Button add;

        public AddHolder(View itemView) {
            super(itemView);
            add = (Button) itemView.findViewById(R.id.btn_add);
        }


    }

    private class TitleHolder extends RecyclerView.ViewHolder {

        TextView title;

        public TitleHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.tv_title);
            title.requestFocus();
        }


    }


    /**
     * Called when a view created by this adapter has been attached to a window.
     * <p/>
     * <p>This can be used as a reasonable signal that the view is about to be seen
     * by the user. If the adapter previously freed any resources in
     * {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
     * those resources should be restored here.</p>
     *
     * @param holder Holder of the view being attached
     */
    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        if (holder instanceof TitleHolder) {
            ((TitleHolder) holder).title.requestFocus();
        }
    }


}
